<template>
	<view v-if="showPopup" class="uni-popup" :class="[popupstyle]" @touchmove.stop.prevent="clear">
		<view class="uni-popup__mask" :style="{ backgroundColor: bg }" @click="onTap"></view>
		<view class="uni-popup__wrapper" :class="[popupstyle]" :style="{ backgroundColor: bg }">
			<slot />
		</view>
	</view>
</template>

<script>
	export default {
		name: 'uniPopup',
		props: {
			// 开启动画
			animation: {
				type: Boolean,
				default: true
			},
			// 弹出层类型，可选值，top: 顶部弹出层；bottom：底部弹出层；center：全屏弹出层
			// message: 消息提示 ; dialog : 对话框
			type: {
				type: String,
				default: 'center'
			},
			// maskClick
			maskClick: {
				type: Boolean,
				default: true
			},
			backgroundColor: {
				type: String,
				default: 'none'
			},
			safeArea: {
				type: Boolean,
				default: true
			},
			maskBackgroundColor: {
				type: String,
				default: 'rgba(0, 0, 0, 0.4)'
			}
		},
		data() {
			return {
				showPopup: false,
				popupstyle: this.type
			}
		},
		computed: {
			bg() {
				if (this.backgroundColor === '' || this.backgroundColor === 'none') {
					return 'transparent'
				}
				return this.backgroundColor
			}
		},
		created() {
			this.popupstyle = this.type
		},
		methods: {
			clear(e) {
				// 取消冒泡
				e.stopPropagation()
			},
			open() {
				this.showPopup = true
				this.$emit('change', {
					show: true,
					type: this.type
				})
			},
			close(type) {
				this.showPopup = false
				this.$emit('change', {
					show: false,
					type: this.type
				})
				this.$emit('maskClick')
			},
			onTap() {
				if (this.maskClick) {
					this.close()
				}
			}
		}
	}
</script>

<style>
	.uni-popup {
		position: fixed;
		z-index: 99;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
	}
	
	.uni-popup__mask {
		position: absolute;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: rgba(0, 0, 0, 0.4);
		opacity: 1;
	}
	
	.uni-popup__wrapper {
		position: absolute;
		box-sizing: border-box;
	}
	
	.uni-popup__wrapper.center {
		width: 100%;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	
	.uni-popup__wrapper.bottom {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		/* iphonex 等安全区设置，底部安全区适配 */
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
	}
	
	.uni-popup.center .uni-popup__mask {
		background-color: rgba(0, 0, 0, 0.4);
	}
	
	.uni-popup.bottom .uni-popup__wrapper {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
	}
</style> 